package com.hancheng.commoncloud.framework.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

/**
 * @description: json工具类
 * @author 金笛
 * @date 2022/1/23 16:05
 */
@Slf4j
public class JacksonUtil {

    public static ObjectMapper objectMapper = new ObjectMapper();
    public static XmlMapper xmlMapper = new XmlMapper();

    public static <T> T readValue(String jsonStr, Class<T> valueType) {
        try {
            return objectMapper.readValue(jsonStr, valueType);
        } catch (Exception var3) {
            log.error("JacksonUtil.readValue error", var3);
            return null;
        }
    }

    public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
        try {
            return objectMapper.readValue(jsonStr, valueTypeRef);
        } catch (Exception var3) {
            log.error("JacksonUtil.readValue error", var3);
            return null;
        }
    }

    public static String toJson(Object object) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (Exception var2) {
            log.error("JacksonUtil.toJson error", var2);
            return null;
        }
    }

    public static String toXml(Object object) {
        try {
            return xmlMapper.writeValueAsString(object);
        } catch (JsonProcessingException var2) {
            log.error("JacksonUtil.toJson error", var2);
            return null;
        }
    }

    public static <T> T readXmlValue(String xml, Class<T> valueType) {
        try {
            return xmlMapper.readValue(xml, valueType);
        } catch (IOException var3) {
            log.error("JacksonUtil.readXmlValue error", var3);
            return null;
        }
    }
}
